// userStore.ts
import { defineStore } from "pinia";
import { loginAPI, getUserInfoAPI } from "@/service/login/login";
import cache from "@/utils/cache";
import { LoginData, UserInfo } from "@/service/login/types";
import { buildMenuTree } from "@/utils";
import Swal from "sweetalert2";
import { jwtDecode } from "jwt-decode";
import { useRouter } from "vue-router";

export const useUserStore = defineStore("user", {
  state: (): UserInfo => ({
    id: null,
    username: "",
    role: null,
    image: [],
    token: cache.getCache("token") || "", // 从缓存中获取 token
    isAuth: false,
    userInfoLoaded: false,
    menuTree: [],
  }),
  actions: {
    // 登录逻辑
    async login(data: LoginData) {
      try {
        const res = await loginAPI(data);
        this.token = res.data;
        this.isAuth = true;
        cache.setCache("token", this.token);
        cache.setCache("isAuth", this.isAuth);
        cache.setCache("userInfoLoaded", this.userInfoLoaded);
        Swal.fire({
          title: "登录成功",
          text: "欢迎使用",
          icon: "success",
        });
        this.checkTokenExpired(); // 在登录成功后调用
      } catch (error) {
        Swal.fire({
          title: "登录失败",
          text: "请检查用户名和密码是否正确",
          icon: "error",
        });
      }
    },
    // 判断token是否过期
    isTokenExpired(): boolean {
      const token = this.token;
      if (!token) {
        return true;
      }
      try {
        const decoded: any = jwtDecode(token);
        const currentTime = Date.now() / 1000; // 当前时间（秒）
        return decoded.exp ? decoded.exp < currentTime : true;
      } catch (error) {
        Swal.fire({
          title: "token过期",
          text: "请重新登录",
          icon: "error",
        });
        return true;
      }
    },
    // 获取用户信息
    async getUserInfo() {
      try {
        const token = cache.getCache("token");
        if (!token) {
          console.error("Token not found");
          return;
        }
        const res = await getUserInfoAPI(token);
        const { id, image, role, username } = res?.data?.data;
        const menus = role?.menus;
        const menuTree = buildMenuTree(menus);

        this.id = id;
        this.username = username;
        this.role = role;
        this.image = image;
        this.menuTree = menuTree;
        return res;
      } catch (error) {
        Swal.fire({
          title: "获取用户信息失败",
          text: "请检查网络是否正常",
          icon: "error",
        });
        const router = useRouter();
        router.push("/login");
        return null;
      }
    },

    // 注销逻辑
    logout() {
      this.id = null;
      this.username = "";
      this.role = null;
      this.image = [];
      this.token = "";
      this.isAuth = false;
      cache.deletCach("token");
      cache.deletCach("isAuth");
      cache.deletCach("userInfoLoaded");
      Swal.fire({
        title: "注销成功",
        text: "欢迎下次使用",
        icon: "warning",
      });
    },
    // 自动注销过期会话
    checkTokenExpired() {
      setInterval(() => {
        if (this.isTokenExpired()) {
          this.logout();
        }
      }, 60000); // 每分钟检查一次
    },
  },
});
